//
//  ZLFDateBaseHandle.m
//  豆瓣综合网页
//
//  Created by 赵立峰 on 16/1/9.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ZLFDateBaseHandle.h"
#import "activityModel.h"
@implementation ZLFDateBaseHandle

+(ZLFDateBaseHandle *)shareActivity {
    static ZLFDateBaseHandle *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[ZLFDateBaseHandle alloc] init];
    });
    return handle;
}

- (void)openDB {
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *dbPath = [document stringByAppendingPathComponent:@"activity.sqlite"];
    NSLog(@"%@", dbPath);
    int result = sqlite3_open(dbPath.UTF8String, &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"数据库打开成功");
    }else {
        NSLog(@"数据库打开失败");
    }
}

- (void)actcreatTabel {
    NSString *sqlStr = [NSString stringWithFormat:@"create table if not exists activity(number integer primary key autoincrement, title text)"];
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"建表成功");
    }else {
        NSLog(@"建表失败");
    }
}

- (void)actinsertTabel:(activityModel *)model {
    NSString *sqlStr = [NSString stringWithFormat:@"insert into activity(title) values('%@')",model.title];
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"插入成功");
    }else {
        NSLog(@"插入失败");
    }
}

- (void)actdeleteTabel:(activityModel *)model {
    NSString *sqlStr = [NSString stringWithFormat:@"delete from activity"];
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"删除成功");
    }else {
        NSLog(@"删除失败");
    }
}

- (NSMutableArray *)actselectTabel {
    NSString *sqlStr = [NSString stringWithFormat:@"select * from activity"];
    sqlite3_stmt *stmt = nil;
    int result = sqlite3_prepare_v2(dbPoint, sqlStr.UTF8String, -1, &stmt, NULL);
    NSMutableArray *arrModel = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *title = sqlite3_column_text(stmt, 1);
            activityModel *model = [activityModel activitymodel];
            model.title = [NSString stringWithUTF8String:(const char *)title];
            [arrModel addObject:model];
            
        }
    }
    
    return arrModel;
    
    
}

@end
